package com.woniu.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.UserPoMapper;
import com.woniu.util.JwtTokenUtil;
import com.woniu.util.ResponseResult;
import com.woniu.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private UserPoMapper userPoMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
       //获得客户端请求的头信息
        String tokenStr = request.getHeader("tokenStr");
        String requestURI = request.getRequestURI().toString();
        if(requestURI.equals("/login")||requestURI.equals("/login.html")){
            filterChain.doFilter(request,response);
            return;
        }

        if (StringUtils.isEmpty(tokenStr)) {
            ResponseResult<String> success = ResponseResult.error(ResultCode.TOKEN_IS_NULL);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(success));
            writer.flush();
            writer.close();
            return;
        }
        try {
            //检测token值是否有效
            if (JwtTokenUtil.checkSign(tokenStr)) {
                //token有效
                //获取token中的用户名
                String username = JwtTokenUtil.getUserId(tokenStr);
                //根据用户名查询数据库的权限标识符信息
                List<String> percodes = userPoMapper.getPercodeByUsername(username);
                List<GrantedAuthority> authorities = new ArrayList<>();
                percodes.forEach(percode -> {
                    authorities.add(new SimpleGrantedAuthority(percode));
                });

                Authentication authentication =
                        new UsernamePasswordAuthenticationToken(username, "", authorities);

                SecurityContextHolder.getContext().setAuthentication(authentication);
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseResult<String> success = ResponseResult.error(ResultCode.TOKEN_INVALID_EXCEPTION);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(success));
            writer.flush();
            writer.close();
        }

    }
}
